import { defineStore } from "pinia";
import { ref } from "vue";
import { login as loginApi } from "@/apis/api";
import { ElMessage } from "element-plus";

export const useTokenStore = defineStore(
  "token",
  () => {
    // 状态
    const accessToken = ref("");
    const userInfo = ref({});
    const permissions = ref([]);

    // actions
    const setAccessToken = (token) => {
      accessToken.value = token;
    };

    const setUserInfo = (info) => {
      userInfo.value = info;
    };

    const setPermissions = (perms) => {
      permissions.value = perms;
    };

    const login = async (loginForm) => {
      try {
        const res = await loginApi(loginForm);
        if (res.code === 200) {
          setAccessToken(res.data.token);
          setUserInfo(res.data.userInfo || {});
          setPermissions(res.data.permissions || []);
          return true;
        } else {
          ElMessage.error(res.message || "登录失败");
          return false;
        }
      } catch (error) {
        ElMessage.error("登录失败，请稍后重试");
        return false;
      }
    };

    const logout = () => {
      accessToken.value = "";
      userInfo.value = {};
      permissions.value = [];
    };

    const hasPermission = (permission) => {
      return permissions.value.includes(permission);
    };

    return {
      // 状态
      accessToken,
      userInfo,
      permissions,
      
      // actions
      setAccessToken,
      setUserInfo,
      setPermissions,
      login,
      logout,
      hasPermission
    };
  },
  {
    persist: {
      // 持久化配置
      key: "token-store",
      storage: localStorage,
      paths: ["accessToken", "userInfo", "permissions"]
    }
  }
);
